package tree;

public class BinaryTree {

    /**
     * 根节点
     */
    private Node root;

    public BinaryTree() {
        this.root = null;
    }

    /**
     * 创建排序二叉树
     *
     * @param value
     */
    public void insertNodeForCreateBinaryTree(String value) {
        Node node = Node.getInstance(value);

        if (null == root) {
            root = node;
        } else {
            insertNode(root, node);
        }
    }

    public void insertNode(Node node, Node newNode) {
        if (newNode.getValue().compareTo(node.getValue()) < 0) {
            //新节点插入左边
            if (node.getLeftNode() == null) {
                node.setLeftNode(newNode);
            } else {
                insertNode(node.getLeftNode(), newNode);
            }
        } else {

            //新节点插入右边
            if (node.getRightNode() == null) {
                node.setRightNode(newNode);
            } else {
                insertNode(node.getRightNode(), newNode);
            }
        }
    }

    /**
     * 中序遍历
     */
    public void inOrderTraverse() {
        inOrderTraverseNode(root);
    }

    private void inOrderTraverseNode(Node node) {
        if (node != null) {
            inOrderTraverseNode(node.getLeftNode());
            System.out.println(node.getValue());
            inOrderTraverseNode(node.getRightNode());
        }
    }

}
